/******************************************************************************
 *                  Shanghai ChipON Micro-Electronic Co.,Ltd                  *
 ******************************************************************************
 *  $File Name$       : main.c                                         	      *
 *  $Author$          : ChipON AE/FAE Group                                   *
 *  $Data$            : 2021-07-8                                             *
 *  $AutoSAR Version  : V1.0	                                              *
 *  $Description$     : This example demonstrates how go to STOP1 sleep mode, *
 * 						and wakeup source									  *
 * 						-Timer0 in STOP1 mode 								  *
 * 						-RTC beat Interrupt in STOP1 mode					  *
 * 						-WKUP pins in STOP1 mode							  *
 ******************************************************************************
 *  Copyright (C) by Shanghai ChipON Micro-Electronic Co.,Ltd                 *
 *  All rights reserved.                                                      *
 *                                                                            *
 *  This software is copyrght protected and proprietary to                    *
 *  Shanghai ChipON Micro-Electronic Co.,Ltd.                                 *
 ******************************************************************************
 *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  *
 *                     		REVISON HISTORY                               	  *
 *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  *
 *  Data       Version  Author        Description                             *
 *  ~~~~~~~~~~ ~~~~~~~~ ~~~~~~~~~~~~  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  *
 *  2021-07-08 00.01.00 FAE Group     new creat                               *
 *                                                                            *
 *                                                                            *
 *****************************************************************************/

/******************************************************************************
**                      		Include Files                                **
******************************************************************************/
#include "system_init.h"

/******************************************************************************
**                      	Private variables                                **
******************************************************************************/
static volatile uint32_t TimingDelay;

/*******************************************************************************
**                     		   Global Functions 		             	      **
*******************************************************************************/
/**
 *  @brief :Initialize the LED GPIO ports
 * 			PD7	------------- UserKey
 * 			PD12 ------------ LED1
 * 			PH3 ------------- LED2
 *  @param in :None
 *  @param out :None 
 *  @retval :None
 */
void BoardGpioInit(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	
	/* Configure PD12 LED1 output */
	GPIO_InitStructure.m_Mode = GPIO_MODE_OUT;
	GPIO_InitStructure.m_OpenDrain = GPIO_POD_PP;
	GPIO_InitStructure.m_PullDown = GPIO_NOPULL;
	GPIO_InitStructure.m_PullUp = GPIO_NOPULL;
	GPIO_InitStructure.m_Speed = GPIO_LOW_SPEED;
	GPIO_InitStructure.m_Pin = GPIO_PIN_MASK_12;
	GPIO_Configuration(GPIOD_SFR , &GPIO_InitStructure);
	/* Configure PH3 LED2 output */
	GPIO_InitStructure.m_Pin = GPIO_PIN_MASK_3;
	GPIO_Configuration(GPIOH_SFR , &GPIO_InitStructure);
	/* Configure PA4 LED3 output */
	GPIO_InitStructure.m_Pin = GPIO_PIN_MASK_4;
	GPIO_Configuration(GPIOA_SFR , &GPIO_InitStructure);
	/* Configure PD7 user key input */
	GPIO_InitStructure.m_Mode = GPIO_MODE_IN;
	GPIO_InitStructure.m_Pin = GPIO_PIN_MASK_7;
	GPIO_Configuration(GPIOD_SFR , &GPIO_InitStructure);
}

/**
 *  @brief :Config the BKP area is enable, BKP register and data can be write and read
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void BKP_WriteReadEnable(void)
{
	/* The backup domain register allows reading and writing */
	SFR_SET_BIT_ASM(OSC_CTL0, OSC_CTL0_PMWREN_POS);
	/* Backup domain exits reset mode */
	SFR_SET_BIT_ASM(PM_CTL0, PM_CTL0_BKPREGCLR_POS);
	/* The backup area allows reading and writing */
	SFR_SET_BIT_ASM(PM_CTL0, PM_CTL0_BKPWR_POS);
}

/**
 *  @brief : Initialize Timer0 and configure it can be runnning in STOP1 mode
 * 			 'BKP_WriteReadEnable' function called must be first!!!
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void Timer0LowPowerInit(void)
{
	GPTIM_InitTypeDef  GPTIM_InitStructure;

	/* Disable the INTLF as the clock of CCP0, and reset the Timer0 */
	PM_CCP0CLKLPEN_Enable(FALSE);
	PM_CCP0LPEN_ENABLE(FALSE);
	GPTIM_Reset(T0_SFR);
	/* Timer0 configured as follow:
		- InputClock = INTLF = 32K
		- Prescal = 2
		- Period = 50000
	 */
	GPTIM_InitStructure.m_Clock = GPTIM_T0_INTLF;
	GPTIM_InitStructure.m_Counter = 0;
	GPTIM_InitStructure.m_CounterMode = GPTIM_COUNT_UP_OF;
	GPTIM_InitStructure.m_MasterSlaveSync = FALSE;
	GPTIM_InitStructure.m_Period = 50000;
	GPTIM_InitStructure.m_Prescaler = 2;
	GPTIM_InitStructure.m_SlaveMode = GPTIM_SLAVE_FORBIDDEN_MODE;
	GPTIM_InitStructure.m_WorkMode = GPTIM_TIMER_MODE;
	GPTIM_Configuration(T0_SFR, &GPTIM_InitStructure);
	/* Enable Timer0, and enable overflow interrupt */
	GPTIM_Cmd(T0_SFR, ENABLE);
	GPTIM_Clear_Overflow_INT_Flag(T0_SFR);
	GPTIM_Overflow_INT_Enable(T0_SFR, ENABLE);
	/* Enable Timer0 running in STOP1 mode */
	PM_Internal_Low_Frequency_Enable(TRUE);
	PM_CCP0LPEN_ENABLE(TRUE);	
	PM_CCP0CLKLPEN_Enable(TRUE);
}

/**
 *  @brief :
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void RTCLowPowerInit(void)
{
	RTC_InitTypeDef RTC_InitStructure;

	/* Reset and enable RTC module */
	RTC_Reset();
	/* Configure the RTC  */
	RTC_InitStructure.m_ClockSource = RTC_WORK_CLK_INTLF;
	RTC_InitStructure.m_DateStruct.m_Year = 21;
	RTC_InitStructure.m_DateStruct.m_Month = 7;
	RTC_InitStructure.m_DateStruct.m_Day = 8;
	RTC_InitStructure.m_TimeStruct.m_Hours = 12;
	RTC_InitStructure.m_TimeStruct.m_Minutes = 0;
	RTC_InitStructure.m_TimeStruct.m_Seconds = 0;
	RTC_InitStructure.m_HourFormat = RTC_HOUR_FORMAT_24;
	RTC_Configuration(RTC_TIME_FORMAT_BIN, &RTC_InitStructure);
	/* Enter RTC configure mode */
	RTC_Config_Mode_Enable(TRUE);
	/* RTC calibration is 0 */
	RTC_Clock_Calibration_Config((int8_t)0x0);
	/* Enable RTC beat interrupt is 1S <1:1> */
	RTC_Time_Tick_Output_Enable(TRUE);
	RTC_Time_Tick_Config(RTC_TIME_TICK_DIV_2);
	RTC_Enable(TRUE);
	/* Exit RTC configure mode */
	RTC_Config_Mode_Enable(FALSE);
	/* Enable Timer0 running in STOP1 mode */
	PM_Internal_Low_Frequency_Enable(TRUE);
	PM_RTC_Reset_Control(TRUE);
	PM_RTC_Work_Stop_INTLF_Enable(TRUE);
}

/**
 *  @brief :
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void RTCBeatInit(void)
{
	EINT_InitTypeDef EINT_17to19;
	/* Configure INT_EINT19TO17 */
    EINT_17to19.m_Rise = TRUE;
    EINT_17to19.m_Fall = FALSE;
	EINT_17to19.m_Mask = TRUE;
    EINT_17to19.m_Line = INT_EXTERNAL_INTERRUPT_17;
    INT_External_Configuration(&EINT_17to19);	
    /* Enable RTC beat interrupt */
	RTC_Clear_Time_Tick_INT_Flag();
    RTC_Time_Tick_INT_Enable(TRUE);
	/* Enable INT_EINT19TO17 */
	INT_Interrupt_Enable(INT_EINT19TO17, TRUE);
	INT_Interrupt_Priority_Config(INT_EINT19TO17, 7, 0);
}

/**
 *  @brief : Initialize the WKUP2 Pin in PC2, WKUP1~5 in this way
 * 			'BKP_WriteReadEnable' function called must be first!!!
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void WakeupPinInit(void)
{
	if (PM_Get_Reset_Flag(PM_WAKEUP_EXTERNAL_PIN_WKP2))
	{
		PM_Clear_External_Wakeup_Pin_Flag(PM_WAKEUP_EXTERNAL_PIN_WKP2);
	}
	PM_External_Wakeup_Pin_Enable(PM_PIN_WKP2, TRUE);
	PM_External_Wakeup_Edge_Config(PM_PIN_WKP2, PM_TRIGGER_RISE_EDGE);
}

/**
 *  @brief :Set the stop1 sleep mode, and go to sleep
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void SystemGotoStop1Mode(void)
{
	/* Set stop1 sleep mode */
	PM_Low_Power_Mode_Config(PM_LOW_POWER_MODE_STOP_1);
	/* Go to sleep */
	asm("SLEEP");
}

/*******************************************************************************
**                     			Main Functions 		             	     	  **
*******************************************************************************/
/**
 *  @brief :Main program
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
int main()
{
	EINT_InitTypeDef EINT_17to19;
	volatile uint32_t i;
	/* Initialize the system clock is 120M */
	SystemInit(120);
	/* Setup SysTick Timer as delay function, and input frequency is 120M */
	systick_delay_init(120);
	/* Initialize the LED IOs */
	BoardGpioInit();
	/* Set the BKP area is enable */
	BKP_WriteReadEnable();
	/* If it is awakened by the RTC beat interrupt, it will enter this statement */
	if (RTC_Get_Time_Tick_INT_Flag() != RESET)
	{
		RTC_Clear_Time_Tick_INT_Flag();
		/* Turn on LED3 to represent wake-up from RTC  */
		GPIO_Toggle_Output_Data_Config(GPIOA_SFR, GPIO_PIN_MASK_4);
	}
	/* Query whether it is WKUP2 pin wakeup, clear WKUP2 flag, and light the LED2 */
	if (PM_Get_Reset_Flag(PM_WAKEUP_EXTERNAL_PIN_WKP2))
	{
		PM_Clear_External_Wakeup_Pin_Flag(PM_WAKEUP_EXTERNAL_PIN_WKP2);
		/* Turn on LED3 to represent wake-up from RTC  */
		GPIO_Toggle_Output_Data_Config(GPIOH_SFR, GPIO_PIN_MASK_3);
	}
	/* Turn ON/OFF the LED1 every 200ms for 10 times, it showing power on state */
	do
	{
		GPIO_Toggle_Output_Data_Config(GPIOD_SFR, GPIO_PIN_MASK_12);
		systick_delay_ms(200);
	} while ((TimingDelay++ < 10));
	INT_All_Enable(TRUE);
#if 1/* Only one of RTC and Timer0 can be selected */
	/* In STOP1 mode, RTC initialize only once to keep the RTC time. BKP data 
	isn't reset in this mode */
	if (BKP_DATA0 == 0)
	{
		BKP_DATA0 = 1;
		RTCLowPowerInit();
	}
    /* Configure and enable INT_EINT19TO17 */
    RTCBeatInit();
#endif
	while(1)
	{
		/* Scan the user key */
		if (GPIO_Read_Input_Data_Bit(GPIOD_SFR, GPIO_PIN_MASK_7) == Bit_RESET)
		{
#if 0		/* Only one of RTC and Timer0 can be selected */
			/* Initialize Timer0, running in STOP1 mode */
			Timer0LowPowerInit();
#endif
			/* Initialize the WKUP2 Pin in PC2 */
			WakeupPinInit();
			/* Go to Sleep */
			SystemGotoStop1Mode();
		}
	}		
}

/**
 *  @brief : Reports the name of the source file and the source line number
 *           where the assert_param error has occurred.
 *  @param in :	file pointer to the source file name
 * 	@param in :	line assert_param error line source number
 *  @param out :None
 *  @retval :None
 */
void check_failed(uint8_t* File, uint32_t Line)
{
	/* User can add his own implementation to report the file name and line number,
		ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

	/* Infinite loop */
	while(1)
	{
		;
	}
};
